<?php
namespace Common\Model;

class LoginLogModel extends Model {
    protected $tableName = 'login_log';
    protected $pk        = 'id';

    /**
     * buildSearchExpr 
     * 组装查询条件
     * 
     * @param mixed $d  查询数据，一般来源于$_GET或$_POST
     * @param mixed $field  可查询的字段对照表，其结构为array(array('表单项目名称' => '数据库字段名称'))
     * @access public
     * @return void 返回值为数组，参见方法内部注释
     */
    public function buildSearchExpr($d, $field = NULL) {
        $expr = array();
        $dao  = array();
        $sortExpr = 'id DESC';

        /**
         * 下标为表单中的项目名称，值为数据库中表的字段名称 
         */
        if(empty($field)) {
            $field = [                
                'create_date' => 'create_time',
                'user_name'   => 'user_name',
                'ip'          => 'ip',
                'status'      => 'status',
                'user_type'   => 'user_type',
            ];
        }

        foreach($field as $k => $v) {
            $tmpExpr = null;
            $val     = isset($d[$k]) ? trim($d[$k]) : '';

            if(strlen($val) < 1) {
                continue;
            }

            switch($k) {
                case 'user_name' :
                    $expr['user_name'] = array('EXP', "LIKE '%{$val}%'");
                    break;

                case 'create_date' : 
                    $tmpExpr = "to_char(create_time, 'YYYY-MM-DD') = '{$val}'";
                    break;

                default:
                    $expr[$v] = $d[$k];
            }

            if(!empty($tmpExpr)) {
                $expr['_string'] = empty($expr['_string'])
                                  ? $tmpExpr
                                  : $expr['_string'] . " AND {$tmpExpr}";
            }

            $dao[$k] = $d[$k];
        }

        if(!empty($d['sort']) && in_array($d['sort'], $this->getDbFields())) {
            $sortdir = empty($d['sortdir'])                     ? 'DESC'   : strtoupper($d['sortdir']);
            $sortdir = in_array($sortdir, array('DESC', 'ASC')) ? $sortdir : 'DESC';

            $sort        = $d['sort'];
            $dao['sort'] = $sort;

            $sortExpr       = "{$sort} {$sortdir}";
            $dao['sortdir'] = $sortdir;
        }

        return array(
            'expr' => $expr,            //ThinkPHP查询条件表达式
            'sort' => $sortExpr,        //排序表达式
            'json' => json_encode($dao) //用于回填至查询表单的数据
        );
    }

    /**
     * log
     * 记录登陆日志
     *
     *$d = array(
     *    'user_name'       => $name,
     *    'passwd'      => $passwd,
     *    'status'      => 0,
     *);
     * @param mixed $d
     * @return void
     */
    public function log($d) {
        $d['create_time'] = date('Y-m-d H:i:s');
        $d['ip']          = getClientIp();

        C('C_DB_WRITE', 1);
        $r = $this->add($d);
        C('C_DB_WRITE', 0);

        return true;
    }

}
